import { _decorator, Color, Component, director, Label, Node, ProgressBar, Sprite, SpriteFrame, error } from 'cc';
import { Core } from '../Core/Core';
import { BattleManager } from '../BattleManager';
import { EScene, GameModeDisplayText } from '../Config/Enum';
import { Util } from '../Util';
import { ResourceManager } from '../Core/ResourceManager';
import { PicPath } from '../Config/ResourceConfig';
import { BagItem } from '../Item/BagItem';

const { ccclass, property } = _decorator;

@ccclass('GameEndView')
export class GameEndView extends Component {

    @property(Node) ndLoot: Node = null!;

    protected onLoad(): void {
        // 如果未在编辑器绑定，尝试自动查找
        if (!this.ndLoot) this.ndLoot = this.node.getChildByName("Loot");
    }

    start() {
        // 分模块初始化，代码结构更清晰
        this.updateResultInfo();
        this.updateStatistics();
        this.updatePlayerInfo();
        this.updateLootInfo();
    }

    /**
     * 更新标题、模式、关隘信息
     */
    private updateResultInfo() {
        const bm = BattleManager.Instance;
        const resultNode = this.node.getChildByName("Result");

        // 1. 标题 (胜利/失败)
        const titleLabel = resultNode.getChildByName("Title").getComponent(Label);
        titleLabel.string = bm.gameResult ? "大捷" : "惜败";
        titleLabel.color = bm.gameResult ? Color.GREEN : Color.RED;

        // 2. 模式名称
        const modeNode = resultNode.getChildByName("Mode");
        const modeName = GameModeDisplayText[Core.Instance.currentMode] || "未知模式";
        this.setLabelText(modeNode.getChildByName("Mode"), "Value", modeName);

        // 3. 关隘数
        this.setLabelText(modeNode.getChildByName("Stage"), "Value", Core.Instance.currentStage.toString());
    }

    /**
     * 更新战斗数据统计 (击杀、资源、加成、城墙损耗)
     */
    private updateStatistics() {
        const bm = BattleManager.Instance;
        const statsNode = this.node.getChildByName("Statistics");

        // 基础数据
        this.setLabelText(statsNode, "Label_KilledEnemy", bm.numOfDeadEnemies.toString());
        this.setLabelText(statsNode, "Label_Prisoner", bm.prisoner.toString());
        this.setLabelText(statsNode, "Label_Food", bm.food.toString());
        this.setLabelText(statsNode, "Label_Gold", bm.gold.toString());
        this.setLabelText(statsNode, "Label_Renown", bm.renown.toString());
        
        // 修为值 (注意：原代码这里用的是 renown，如果确实是 exp 请改为 bm.exp)
        this.setLabelText(statsNode, "Label_Exp", bm.renown.toString()); 

        // 加成百分比 (处理可能为空的情况)
        this.setLabelText(statsNode, "Label_GoldPercent", (bm.goldPercent || "0") + "%");
        this.setLabelText(statsNode, "Label_ExpPercent", (bm.expPercent || "0") + "%");
        this.setLabelText(statsNode, "Label_RenownPercent", (bm.renownPercent || "0") + "%");

        // 城墙损耗计算
        const hpBegin = Number(bm.wallHpBegin) || 0;
        const hpEnd = Number(bm.wallHpEnd) || 0;
        const damageTaken = Math.max(0, Math.round(hpBegin - hpEnd));
        this.setLabelText(statsNode, "Label_WallDamage", damageTaken.toString());
    }

    /**
     * 更新玩家列表 (伤害、修为、头像)
     */
    private updatePlayerInfo() {
        const bm = BattleManager.Instance;
        const playerList = bm.playerList;
        const damageNode = this.node.getChildByName("DamageAndEXP");
        const totalDamage = Math.max(1, bm.damageTotal); // 防止除以0

        // 1. 先隐藏所有玩家槽位
        damageNode.children.forEach(child => child.active = false);

        // 2. 遍历实际玩家数据
        for (let i = 0; i < playerList.length; i++) {
            const pm = playerList[i];
            const playerType = pm.playerType;
            const playerData = Core.Instance.players.get(playerType);
            const playerNameNode = "Player" + (i + 1);
            const ndPlayer = damageNode.getChildByName(playerNameNode);

            if (!ndPlayer) continue;

            ndPlayer.active = true;

            // --- 头像异步加载 ---
            const avatarPath = `${PicPath[playerType + "Avatar"]}/spriteFrame`;
            ResourceManager.Instance.loadRes<SpriteFrame>(avatarPath, SpriteFrame).then((spriteFrame) => {
                if (this.isValid && ndPlayer && ndPlayer.isValid) {
                    ndPlayer.getChildByName("Avatar").getComponent(Sprite).spriteFrame = spriteFrame;
                }
            }).catch((error) => {
                console.warn(`加载玩家头像失败: ${playerType}`, error);
            });

            // --- 伤害统计 ---
            const damage = bm.playerDamageMap.get(playerType) || 0;
            const damageRatio = damage / totalDamage;
            const damageNodePart = ndPlayer.getChildByName("Damage");
            
            // 伤害数值
            damageNodePart.getChildByName("LB_Damage").getComponent(Label).string = Util.roundToInt(damage).toString();
            // 伤害百分比文字
            damageNodePart.getChildByName("LB_DamagePercent").getComponent(Label).string = Util.roundToInt(damageRatio * 100) + "%";
            // 伤害进度条
            damageNodePart.getChildByName("ProgressBar").getComponent(ProgressBar).progress = damageRatio;

            // --- 修为与升级 ---
            const expPart = ndPlayer.getChildByName("Exp");
            const expBar = expPart.getChildByName("Exp");
            
            // 修为文字
            expBar.getChildByName("Label").getComponent(Label).string = `${playerData.exp}/${playerData.expToNextLevel}`;
            // 修为进度条
            expBar.getComponent(ProgressBar).progress = playerData.exp / playerData.expToNextLevel;

            // 升级提示
            const levelUpNode = expPart.getChildByName("isLevelUp");
            if (levelUpNode) {
                levelUpNode.active = playerData.isLevelUp;
                if (playerData.isLevelUp) {
                    playerData.isLevelUp = false; // 消费掉升级状态
                }
            }
        }
    }

    /**
     * 更新战利品背包
     */
    private updateLootInfo() {
        const lootList = BattleManager.Instance.lootList;
        
        if (!lootList || lootList.length === 0) {
            this.ndLoot.active = false;
            return;
        }

        this.ndLoot.active = true;
        const content = this.ndLoot.getChildByName("Bag").getChildByName("ScrollView").getChildByName("view").getChildByName("content");
        
        // 1. 先隐藏所有格子
        content.children.forEach(child => child.active = false);

        // 2. 填充数据
        for (let i = 0; i < lootList.length; i++) {
            const nodeName = "Loot" + (i + 1);
            const lootItemNode = content.getChildByName(nodeName);
            
            if (lootItemNode) {
                lootItemNode.active = true;
                const bagItemComp = lootItemNode.getComponent(BagItem);
                if (bagItemComp) {
                    bagItemComp.init(lootList[i]);
                }
            }
        }
    }

    /**
     * 辅助方法：设置 Label 文本，支持查找子节点
     * @param parent 父节点
     * @param childName 包含Label组件的子节点名称 (如果Label就在parent上，传null或空字符串)
     * @param text 文本内容
     */
    private setLabelText(parent: Node, childName: string, text: string) {
        if (!parent) return;
        
        let labelNode = parent;
        if (childName) {
            // 这里针对你的结构优化：Label_KilledEnemy -> Value -> Label
            // 如果你的结构是 Label_KilledEnemy 节点下有名为 "Value" 的子节点带 Label
            const target = parent.getChildByName(childName);
            if (target) {
                const valueNode = target.getChildByName("Value");
                if (valueNode && valueNode.getComponent(Label)) {
                    valueNode.getComponent(Label).string = text;
                    return;
                }
                // 或者是直接在 childName 上
                if (target.getComponent(Label)) {
                    target.getComponent(Label).string = text;
                    return;
                }
            }
        }
    }

    onButtonGoMain() {
        // 调用 BattleManager 的退出逻辑，确保清理和保存
        BattleManager.Instance.onButtonGoMain();
    }
}